package supplier

import (
	"context"
	"errors"
	supplierDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/supplier"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/bigdata"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type SupplierService struct {
	supplierRepo SupplierRepositoryIface
}

func NewSupplier(supplierRepo SupplierRepositoryIface) SupplierServiceIface {
	return &SupplierService{
		supplierRepo: supplierRepo,
	}
}

func (s *SupplierService) GetSupplierMainDataMultiName(ctx context.Context, supplierNameList []string) (*supplierDto.CheckSupplierMainDataResponse, error) {
	checkSupplierMainDataResponse := &supplierDto.CheckSupplierMainDataResponse{}
	if len(supplierNameList) == 0 {
		return &supplierDto.CheckSupplierMainDataResponse{}, nil
	}
	var subSupplierNameList []string
	// 最大允许10个
	if len(supplierNameList) >= 10 {
		subSupplierNameList = supplierNameList[:10]
	} else {
		subSupplierNameList = supplierNameList[:]
	}
	request := &bigdata.GetSupplierListRequest{
		SupplierName: strings.Join(subSupplierNameList, ","),
	}
	bigDataResponse, err := s.supplierRepo.GetSupplierList(ctx, request)
	if err != nil {
		return &supplierDto.CheckSupplierMainDataResponse{}, err
	}
	if bigDataResponse.ErrCode != 0 {
		stark.Logger.Errorf(ctx, "数芯接口异常:%s,错误信息:%s", constants.BigDataPathSupplierList, bigDataResponse.ErrMsg)
		return nil, errors.New("数芯接口返回异常")
	}
	//checkSupplierMainDataResponse.Suppliers = []*supplierDto.CheckSupplierMainData{}
	for _, supplierName := range subSupplierNameList {
		checkSupplierMainData := &supplierDto.CheckSupplierMainData{}
		checkSupplierMainData.SupplierName = supplierName
		checkSupplierMainData.IsInMainData = 0
		for _, row := range bigDataResponse.Data.Rows {
			if row["supplier_name"] == supplierName {
				checkSupplierMainData.IsInMainData = 1
				checkSupplierMainData.OrganizingCode = row["organizing_code"].(string)
			}
		}
		checkSupplierMainDataResponse.Suppliers = append(checkSupplierMainDataResponse.Suppliers, checkSupplierMainData)
	}
	return checkSupplierMainDataResponse, nil
}
